package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;


    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        redisTemplate.delete("dish" + dishDto.getCategoryId());
        return R.success("添加成功");
    }

    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        //分页构造器
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class)
                .like(StringUtils.isNotBlank(name), Dish::getName, name)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);

        Page<DishDto> pageInfo2 = new Page<>();
        dishService.page(pageInfo1, queryWrapper);
        //使用工具类把将pageInfo1的属性拷贝到pageInfo2里面，除了records集合外
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");

        //获取到pageInfo1的records
        List<Dish> dishList = pageInfo1.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //将dish数据copy到dishDto中去
            BeanUtils.copyProperties(dish, dishDto);
            //获取Category中的菜品名
            Category category = categoryService.getById(dish.getCategoryId());
            String categoryName = category.getName();
            //把Category中的菜品名添加到dishDto的CategoryName里
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);
    }

    @GetMapping("{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateWithFlavor(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);
        return R.success("更新数据成功");
    }

    @DeleteMapping
    public R<String> deleteWithFlavor(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @Transactional
    public R<String> update(@PathVariable Integer status, @RequestParam List<Long> ids) {
        Dish dish = new Dish();
        dish.setStatus(status);
        ids.forEach(id -> {
            LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class).eq(Dish::getId, id);
            dishService.update(dish, queryWrapper);
        });
        return R.success("更新成功");
    }

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish) {
        //动态构造key
        String dishList = "dish" + dish.getCategoryId();
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishList);
        if (dishDtoList != null) {
            R.success(dishDtoList);
        }
        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = Wrappers.lambdaQuery(Dish.class)
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(wrapper);
        //创建集合
        List<DishDto> dtoList = new ArrayList<>();
        //遍历集合
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper = Wrappers.lambdaQuery(DishFlavor.class)
                    .eq(dish1.getId() != null, DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(dishList, dtoList);
        return R.success(dtoList);
    }
}
